package cn.zhejianglao.shirotemplate.service.file;

import cn.zhejianglao.shirotemplate.common.model.FileVO;
import cn.zhejianglao.shirotemplate.common.model.PagedResult;
import cn.zhejianglao.shirotemplate.common.model.Response;
import cn.zhejianglao.shirotemplate.service.file.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private IFileService fileService;

    @PostMapping("/upload")
    public Response<String> upload(
            @RequestParam(value = "file") MultipartFile file, @RequestParam("path") String path) {
        fileService.upload(file, path);
        return Response.success();
    }

    @GetMapping("/download")
    public void download(@RequestParam("path") String path, @RequestParam("filename") String filename, HttpServletResponse response) {
        fileService.download(path, filename, response);
    }

    @DeleteMapping("/delete")
    public Response<String> delete(@RequestParam("path") String path, @RequestParam("filename") String filename) {
        boolean result = fileService.delete(path, filename);
        if (result) {
            return Response.success();
        }
        return Response.fail("无法删除文件");
    }

    @GetMapping("/list/{size}/{page}")
    public Response<PagedResult<FileVO>> list(@PathVariable("size") int size, @PathVariable("page") int page) {
        return Response.success(fileService.list(size, page));
    }
}
